package com.pucheng.bracelet.ui.activity

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import androidx.lifecycle.distinctUntilChanged
import androidx.lifecycle.observe
import com.blankj.utilcode.util.LogUtils
import com.pucheng.bracelet.R
import com.pucheng.bracelet.app.ext.REQUEST_CODE_TO_NO_DISTURB
import com.pucheng.bracelet.app.ext.REQUEST_CODE_TO_QUICK_VIEW_PERIOD
import com.pucheng.bracelet.app.ext.REQUEST_CODE_TO_USERINFO
import com.pucheng.bracelet.app.util.CacheUtil
import com.pucheng.bracelet.app.util.click
import com.pucheng.bracelet.app.weight.UnitPopup
import com.pucheng.bracelet.databinding.ActivitySettingBinding
import com.pucheng.bracelet.ui.activity.watch.DoNotDisturbActivity
import com.pucheng.bracelet.ui.activity.watch.EffectivePeriodActivity
import com.pucheng.bracelet.viewmodel.SettingViewModel
import com.zaaach.citypicker.CityPicker
import com.zaaach.citypicker.adapter.OnPickListener
import com.zaaach.citypicker.model.City
import com.zaaach.citypicker.model.LocateState
import com.zaaach.citypicker.model.LocatedCity
import com.zaaach.citypicker.util.CityComparator
import kotlinx.android.synthetic.main.activity_setting.*
import kotlinx.android.synthetic.main.layout_title.*
import me.hgj.jetpackmvvm.base.activity.BaseVmDbActivity
import me.hgj.jetpackmvvm.demo.app.base.BaseActivity
import me.hgj.jetpackmvvm.ext.getAppViewModel
import java.util.*

class SettingActivity : BaseActivity<SettingViewModel, ActivitySettingBinding>() {

    override fun layoutId(): Int = R.layout.activity_setting

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.apply {
            viewModel = mViewModel
            appVM = appViewModel
            lifecycleOwner = this@SettingActivity
            ibtn_back.apply {
                setOnClickListener {
                    finish()
                }
            }
            tv_title.apply {
                text = "其他设置"
            }
            //查找手表
            tvFindWatch.click { mViewModel.findWatch() }
            //恢复出厂设置
            tvRestoreSysSetting.click {
                mViewModel.reStoreSysSetting()
            }

            clTimeUnit.click {
                UnitPopup(
                    this@SettingActivity,
                    mViewModel.is12Unit.value!!, tvSetUnit.text.toString()
                ) { is12Unit: Boolean, unitName: String ->
                    tvSetUnit.text = unitName
                    if (mViewModel.is12Unit.value != is12Unit) {
                        mViewModel.chageTimeUnit(is12Unit)
                    }
                }.show(clSetting)

            }
            clQuickViewPeriod.click {
                startActivityForResult(
                    Intent(
                        this@SettingActivity,
                        EffectivePeriodActivity::class.java
                    ), REQUEST_CODE_TO_QUICK_VIEW_PERIOD
                )
            }
            clDoNotDisturb.click {
                startActivityForResult(
                    Intent(
                        this@SettingActivity,
                        DoNotDisturbActivity::class.java
                    ), REQUEST_CODE_TO_NO_DISTURB
                )
            }
            clCity.click { selectCity() }

            sbSit.setOnCheckedChangeListener { _, isChecked ->
                mViewModel.sitForALongHintRemind(
                    isChecked
                )
            }
            sbWeather.setOnCheckedChangeListener { _, isChecked ->
                CacheUtil.setCheckWeather(isChecked)
                appViewModel.isCheckWeather.value = isChecked
            }
            sbHeart.setOnCheckedChangeListener { _, isChecked -> mViewModel.openHRMeasure(isChecked) }
            sbQuickView.setOnCheckedChangeListener { _, isChecked ->
                mViewModel.openQuickView(
                    isChecked
                )
            }
        }
        mViewModel.apply {
            is12Unit.observe(this@SettingActivity) {
                LogUtils.e("${if (it) "12小时制" else "24小时制"}")
            }
            isSitRemind.observe(this@SettingActivity) {
                sb_sit.isChecked = it
            }
            isOpenHRMeasure.observe(this@SettingActivity) {
                sb_heart.isChecked = it
            }
            isQuickView.observe(this@SettingActivity) {
                sb_quick_view.isChecked = it
            }
            isQuickView.observe(this@SettingActivity) {
                sb_quick_view.isChecked = it
            }
            bind.observe(this@SettingActivity) {
                appViewModel.bleConnectStatus.value = true
            }
        }
        appViewModel.apply {
            isCheckWeather.observe(this@SettingActivity) {
                sb_weather.isChecked = it
            }
        }
    }

    private fun selectCity() {
        mViewModel.getCitys()
    }

    override fun createObserver() {
        mViewModel.apply {
            cityDatas.observe(this@SettingActivity, androidx.lifecycle.Observer {
                CityPicker.from(this@SettingActivity)
                    .enableAnimation(false)
                    .setLocatedCity(null)
                    .setAllCities(it)
//            .setHotCities(hotCities)
                    .setOnPickListener(object : OnPickListener {
                        override fun onPick(
                            position: Int,
                            data: City
                        ) {
//                            tv_city.text = data.name
                            appViewModel.selectCity.value = data
                            CacheUtil.setCityInfo(data)
                        }

                        override fun onCancel() {
                            //取消选择
                        }

                        override fun onLocate() {
                            //开始定位，这里模拟一下定位
                            Handler().postDelayed({
                                CityPicker.from(this@SettingActivity).locateComplete(
                                    CacheUtil.getLocationCityInfo(),
                                    LocateState.SUCCESS
                                )
                            }, 3000)
                        }
                    })
                    .show()
            })
            doNotDisturb.observe(this@SettingActivity, androidx.lifecycle.Observer {
                if (!TextUtils.isEmpty(it)) {
                    val startTime = it.split("-")[0]
                    val endTime = it.split("-")[1]
                    if (startTime == endTime) {
                        tv_do_not_disturb.text = getString(R.string.closeed)
                    } else {
                        tv_do_not_disturb.text = it
                    }
                } else {
                    tv_do_not_disturb.text = getString(R.string.closeed)
                }
            })
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUEST_CODE_TO_NO_DISTURB -> mViewModel.doNotDisturb.value =
                CacheUtil.getDoNotDisturb()
            REQUEST_CODE_TO_QUICK_VIEW_PERIOD -> mViewModel.effectivePeriodTime.value = CacheUtil.getQuickViewPeriod()

        }
    }

}